package com.hmdp.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClint;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    /*
     * 查询店铺类型并缓存
     * */
    @Override
    public Result queryTypeList() {
//        // 1.查询商铺缓存
        List<String> shopTypeJson = stringRedisTemplate.opsForList().range(CACHE_SHOP_TYPE_KEY, 0, -1);
//        2.判断是否存在
        if(CollectionUtil.isNotEmpty(shopTypeJson)){
            //        // 3.存在，直接返回
            List<ShopType> list = JSONUtil.toList(shopTypeJson.toString(), ShopType.class);
//            排序
            Collections.sort(list,((o1, o2) -> o1.getSort() - o2.getSort()));
        }


//        // 4.不存在，根据id查询数据库
        List<ShopType> shopTypes = query().orderByAsc("sort").list();
//        // 5.不存在，返回错误
        if(CollectionUtil.isEmpty(shopTypes)){
            return Result.fail("店铺不存在");
        }
//        // 6.存在，写入缓存
//        把集合转成json字符串
        List<String> shopTypesJson = shopTypes.stream().map(shopType -> JSONUtil.toJsonStr(shopType))
                .collect(Collectors.toList());
        stringRedisTemplate.opsForList().rightPushAll(CACHE_SHOP_TYPE_KEY,shopTypesJson);
//        // 7.返回商铺信息
        return Result.ok(shopTypes);
    }
}
